package com.gzhryc.log;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.json.JsonTools;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;


import com.gzhryc.log.enums.HttpLogEnum;
import com.gzhryc.log.models.IDateFragmentInfo;
import com.gzhryc.log.models.IHttpRequestInfo;

import eu.bitwalker.useragentutils.DeviceType;
import eu.bitwalker.useragentutils.UserAgent;

public class HttpLogUtils {

	/**
	 * 获取HTTP请求中的信息
	 * @param request
	 * @param record
	 */
	public static <T extends IHttpRequestInfo> void setHttpRequestInfo(HttpServletRequest request,T record) {
		record.setContextPath(request.getContextPath());
		record.setPath(request.getRequestURI());
		record.setMethod(request.getMethod());
		record.setQueryString(request.getQueryString());
		if(request.getMethod().toUpperCase().equals("POST")) {
			Map<String,String[]> data = request.getParameterMap();
			if(data != null) {
				Map<String,String> json = new HashMap<String,String>();
				for(String name : data.keySet()) {
					String[] temp = data.get(name);
					if(temp != null && temp.length > 0) {
						if(temp[0].length() < 1024) {
							json.put(name, temp[0]);
						}
					}
				}
				record.setFormJson(JsonTools.toJson(json));
			}
		}
		record.setScheme(request.getScheme());
		record.setIp(request.getRemoteAddr());
		record.setAccept(request.getHeader(HttpHeaders.ACCEPT));
		record.setReferer(request.getHeader(HttpHeaders.REFERER));
		
		String userAgentStr = request.getHeader(HttpHeaders.USER_AGENT);
		record.setUserAgent(userAgentStr);
		
		UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr);
		record.setVisitSoftwareName(userAgent.getBrowser().getName());
		if(DeviceType.MOBILE.equals(userAgent.getOperatingSystem().getDeviceType())
				|| DeviceType.TABLET.equals(userAgent.getOperatingSystem().getDeviceType())){
			record.setClientType(HttpLogEnum.ClientType.Mobile.index());
		}else{
			record.setClientType(HttpLogEnum.ClientType.PC.index());
		}
		String xrequestedWith = request.getHeader("X-Requested-With");
		if(StringUtils.isNotBlank(xrequestedWith) && xrequestedWith.equals("XMLHttpRequest")){
			record.setIsXmlHttpRequest(true);
		}else{
			record.setIsXmlHttpRequest(false);
		}
	}
	
	/**
	 * 设置分拆的时间信息
	 * @param record
	 * @param date
	 */
	public static <T extends IDateFragmentInfo> void setDateFragmentInfo(T record,Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		record.setYear(calendar.get(Calendar.YEAR));
		record.setMonth(calendar.get(Calendar.MONTH) + 1);
		record.setDay(calendar.get(Calendar.DAY_OF_MONTH));
		record.setHour(calendar.get(Calendar.HOUR_OF_DAY));
		record.setMinute(calendar.get(Calendar.MINUTE));
	}
}
